package com.education.mail;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by zhangshijie on 2015/8/9.
 */
@Component
public class ThirdVelocityEmail {

	private static final String CODE_TYPE = "UTF-8";
	@Resource
	private JavaMailSender mailSender;
	@Resource
	private VelocityEngine velocityEngine;

	private ExecutorService executor = Executors.newFixedThreadPool(4); //定义容量为4的线程池

	/**
	 * 发送邮件
	 *
	 * @param model
	 * @param subject
	 * @param vmFile
	 * @param mailTo
	 * @param files
	 */
	public void sendEmail(final Map<String, Object> model, final String subject, final String vmFile, final String[] mailTo, final String[] files) {
		Thread t;
		for (String recevier : mailTo) {
			t = new Thread(new SendEmailThread(recevier, subject, vmFile, model, files));
			executor.execute(t);
		}
	}

	public class SendEmailThread implements Runnable {
		private String mailTo;
		private String subject;
		private String vmFile;
		private Map<String, Object> model;
		private String[] files;

		public SendEmailThread(String mailTo, String subject, String vmFile, Map<String, Object> model, String[] files) {
			this.mailTo = mailTo;
			this.subject = subject;
			this.vmFile = vmFile;
			this.model = model;
			this.files = files;
		}

		@Override
		public void run() {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {
				//注意MimeMessagePreparator接口只有这一个回调函数
				public void prepare(MimeMessage mimeMessage) throws Exception {
					MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, CODE_TYPE);
					//这是一个生成Mime邮件简单工具，如果不使用GBK这个，中文会出现乱码
					//如果您使用的都是英文，那么可以使用MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
					message.setTo(mailTo);//设置接收方的email地址
					message.setSubject(subject);//设置邮件主题
					message.setFrom("baolongcnmd@qq.com");//设置发送方地址
					String text = VelocityEngineUtils.mergeTemplateIntoString(
							velocityEngine, "email/template/" + vmFile, CODE_TYPE, model);
					//从模板中加载要发送的内容，vmfile就是模板文件的名字
					//注意模板中有中文要加GBK，model中存放的是要替换模板中字段的值
					message.setText(text, true);
					//将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
					//如果您不想解析文本内容，可以使用false或者不添加这项
					FileSystemResource file;
					//添加附件
					for (String s : files){
						file = new FileSystemResource(new File(s));//读取附件
						message.addAttachment(s, file);//向email中添加附件
					}
				}
			};

			mailSender.send(preparator);//发送邮件
		}
	}

}